package com.xbdun.web.validatebmp.controller.qr;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.enums.XbdunPkgEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.util.CommonUtil;
import com.xbdun.facade.validatebmp.exceptions.ValidateBizException;
import com.xbdun.facade.validatebmp.request.GeneroQrCodeKeyRequest;
import com.xbdun.facade.validatebmp.request.GenroScanQrRequest;
import com.xbdun.facade.validatebmp.request.WxUnionCallRequest;
import com.xbdun.web.validatebmp.service.QrCodeService;
import com.xbdun.web.validatebmp.utils.http.ControllerUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: LoginQrSysController
 * @Description 后台系统登录二维码
 * @author zhanggt 360730440@qq.com
 * @date 2017年5月1日 下午4:05:00
 */
@Controller
@Slf4j
public class LoginQrSysController extends BaseQrController {
	@Autowired
	QrCodeService qrCodeService;

	//生成二维码KEY,然后在调用 genroScanQr
	@RequestMapping(value = "genroQrCodeKey", method = { RequestMethod.GET, RequestMethod.POST })
	public void generoQrCodeKey(GeneroQrCodeKeyRequest request,HttpServletResponse response,HttpServletRequest currentRequest){
		XbdUnStringResult result = new XbdUnStringResult();
		result.setBizException(BizException.ERROR);
		try {
			chekedGeneroQrCodeKey(request);
			String settingPwd = CommonUtil.settingPwd(request.getScanQrKey()+request.getNonceStr()+request.getTimestamp()+ControllerUtil.getIpAddr(currentRequest),request.getTimestamp());
			if(StringUtils.isNotBlank(settingPwd)){
				result.setBizException(BizException.SUCCESS);
				result.setData(settingPwd);
			}
			//打印JSON回调函数
			ControllerUtil.printHtml(response,request.getCallback()+"("+JSON.toJSONString(result)+")");
		} catch (Exception e) {
			log.info("生成扫码内容异常,{}",e);
		}
	}
	
	/**
	* @Title: genroScanQr
	* @Description	根据 上方法【genroQrCodeKey】生成值，填入：scanQrValue中进行校验
	* @param response
	* @param request    设定文件
	* @return void    返回类型
	 */
	@RequestMapping(value = "genroScanQr", method = { RequestMethod.GET, RequestMethod.POST })
	public void genroScanQr(HttpServletResponse response, GenroScanQrRequest request,HttpServletRequest currentRequest) {
		try {
			if(StringUtils.isBlank(request.getTimestamp())){
				ServletOutputStream outputStream = response.getOutputStream();
				outputStream.write("客户端刷新时间不能为空".getBytes("utf-8"));
				outputStream.flush();
			}
			if (StringUtils.isBlank(request.getScanQrKey())||StringUtils.isBlank(request.getScanQrValue())) {
				ServletOutputStream outputStream = response.getOutputStream();
				outputStream.write("生成二维码扫码KEY/值未定义".getBytes("utf-8"));
				outputStream.flush();
				return;
			}
			String ipAddress = ControllerUtil.getIpAddr(currentRequest);
			String settingPwd = CommonUtil.settingPwd(request.getScanQrKey()+request.getNonceStr()+request.getTimestamp()+ipAddress,request.getTimestamp());
			if(!settingPwd.equals(request.getScanQrValue())){
				log.warn("希望生成的二维码与之前定义的二维码内容不一致，非法,"+settingPwd+"!={}",request.getScanQrValue());
				return;
			}
			// 打印二维码内容
			qrCodeService.printGenroQr(ipAddress,request,response,"qr/valiQr.zhtm");
		} catch (Exception e) {
			log.error("生成二维码异常,{}",e);
		}
	}

	
	/**
	* @Title: validateScanQr
	* @Description	验证二维码登录是否有效了
	* @param request	请求对象
	* @return XbdUnStringResult    返回类型
	 */
	@RequestMapping(value = "valiQr.zhtm", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public XbdUnStringResult validateScanQr(WxUnionCallRequest request) {
		XbdUnStringResult result = new XbdUnStringResult();
		result.setBizException(BizException.ERROR);
		try {
			log.info("start 校验二维码是否合法,入参:{}",request);
			chekedValidateScanQr(request);
			if(!qrCodeService.validateInputQr(request)){
				result.setBizException(ValidateBizException.REDIS_VALI_FAIL);
			}else{
				result.setBizException(BizException.SUCCESS);
				result.setData(request.getData());
			}
		} catch (Exception e) {
			result.setBizException(e);
			log.error("校验二维码是否合法,异常:{}",e);
		}finally{
			log.info("end 校验二维码是否合法,结果:{}",result);
		}
		return result;
	}

	/**
	* @Title: chekedValidateScanQr
	* @Description	验证二维码扫码信息
	* @param request    设定文件
	* @return void    返回类型
	 */
	private void chekedValidateScanQr(WxUnionCallRequest request) {
		StringBuilder sb = new StringBuilder();
		XbdunPkgEnum pkgEnum = XbdunPkgEnum.getEnum(request.getPkgName());
		if(null == pkgEnum){
			sb.append("参数包名未定义;");
		}
		if(StringUtils.isBlank(request.getWxUnionId())){
			sb.append("微信统一统一UnionId不能为空;");
		}
		if(StringUtils.isBlank(request.getData())){
			sb.append("扫码的KEY不能为空;");			
		}
		if(sb.length()>0){
			throw BizException.PARAM_CHKE_FAIL.newInstance("校验失败,%s", sb.toString());
		}
		//验证签名
		/*if(null!=pkgEnum){
			//验证包签名是否正确
			if(!MacUtil.validateMac(request, MacUtil.DEF_ACCOUNT_KEY, pkgEnum.getSecritVal())){
				sb.setLength(0);
				throw BizException.TOKEN_IS_ILLICIT.newInstance("对不起，您的签名错误");
			}
		}*/
		sb = null;
	}
	
	//检测生成二维码KEY
	private void chekedGeneroQrCodeKey(GeneroQrCodeKeyRequest request) {
		StringBuilder sb = new StringBuilder();
		if(StringUtils.isBlank(request.getNonceStr())){
			sb.append("随机码不能为空;");
		}
		if(StringUtils.isBlank(request.getScanQrKey())){
			sb.append("扫码的KEY不能为空;");			
		}
		if(StringUtils.isBlank(request.getTimestamp())||!NumberUtils.isDigits(request.getTimestamp())){
			sb.append("扫码时间戳格式不正确;");			
		}
		if(StringUtils.isEmpty(request.getCallback())){
			sb.append("回调函数不能为空;");	
		}
		if(sb.length()>0){
			throw BizException.PARAM_CHKE_FAIL.newInstance("校验失败,%s", sb.toString());
		}
		sb = null;
	}
}
